package com.yunwaikeji.gy_tool_library.widget;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.yunwaikeji.gy_tool_library.R;

/**
 * 增加减少数量控件
 * 郭杨
 * 2019/07/09
 */
public class GYPlusReduceView extends LinearLayout {
    private float reduceWidth;
    private float numberWidth;
    private float plusWidth;
    private int minNumber;
    private int maxNumber;
    private int number;
    private boolean isFull;

    private TextView reduceTextView;
    private TextView numberTextView;
    private TextView plusTextView;

    private int clickColor = Color.BLACK;
    private int noClickColor = Color.GRAY;
    private float numberSize;
    private float radius;

    private int edgeWidthPx;
    private int edgeColor;
    private float leftDivider;
    private int leftDividerColor;
    private float rightDivider;
    private int rightDividerColor;
    private float reduceSize;
    private float plusSize;
    private int reduceDrawable;
    private int plusDrawable;
    private float divider;
    private int dividerColor;

    private int backgroundColor;

    private LinearLayout reduceLL;
    private LinearLayout numberLL;
    private LinearLayout plusLL;

    private View leftDividerView;
    private View rightDividerView;

    private ImageView reduceImageView;
    private ImageView plusImageView;

    private int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;
    private int MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT;

    private OnNumberChangedListener onNumberChangedListener;

    public GYPlusReduceView(Context context) {
        super(context);
    }

    public GYPlusReduceView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public GYPlusReduceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    @SuppressLint("NewApi")
    public GYPlusReduceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }

    private View view(int width, int color) {
        View view = new View(getContext());
        view.setLayoutParams(new LayoutParams(width, MATCH_PARENT));
        view.setBackgroundColor(color);
        return view;
    }

    private ImageView imageView(int resId, int width, int height) {
        ImageView imageView = new ImageView(getContext());
        imageView.setImageResource(resId);
        imageView.setLayoutParams(new LayoutParams(width, height));
        return imageView;
    }

    private TextView textView(String text, int size) {
        TextView textView = new TextView(getContext());
        textView.setText(text);
        textView.setTextSize(px2sp(getContext(), size));
//        textView.setBackground(getDrawable(Color.WHITE, 1, Color.BLACK, Math.round(radius)));
        textView.setSingleLine(true);
        return textView;
    }

    private LinearLayout linearLayout(int width, int height) {
        LinearLayout linearLayout = new LinearLayout(getContext());
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setMinimumWidth(dp2px(getContext(), 20));
//        linearLayout.setBackground(getDrawable(Color.WHITE, 1, Color.BLACK, Math.round(radius)));
        linearLayout.setGravity(Gravity.CENTER);
        if (isFull) {
            linearLayout.setLayoutParams(new LayoutParams(0, MATCH_PARENT, 1));
        } else {
            linearLayout.setLayoutParams(new LayoutParams(width, height));
        }
        return linearLayout;
    }

    private void init(AttributeSet attributeSet) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attributeSet, R.styleable.GYPlusReduceView);
        reduceWidth = typedArray.getDimension(R.styleable.GYPlusReduceView_reduceWidth, dp2px(getContext(), 14));
        numberWidth = typedArray.getDimension(R.styleable.GYPlusReduceView_numberWidth, dp2px(getContext(), 20));
        plusWidth = typedArray.getDimension(R.styleable.GYPlusReduceView_plusWidth, dp2px(getContext(), 14));
        minNumber = typedArray.getInteger(R.styleable.GYPlusReduceView_minNumber, -99999);
        maxNumber = typedArray.getInteger(R.styleable.GYPlusReduceView_maxNumber, 99999);
        number = typedArray.getInteger(R.styleable.GYPlusReduceView_number, 1);
        isFull = typedArray.getBoolean(R.styleable.GYPlusReduceView_isFull, false);
        numberSize = typedArray.getDimension(R.styleable.GYPlusReduceView_numberSize, sp2px(getContext(), 14));
        radius = typedArray.getDimension(R.styleable.GYPlusReduceView_radius, 0);

        backgroundColor = typedArray.getInteger(R.styleable.GYPlusReduceView_backgroundColor, 0);

        edgeWidthPx = typedArray.getDimensionPixelSize(R.styleable.GYPlusReduceView_edgeWidth, 0);
        edgeColor = typedArray.getInteger(R.styleable.GYPlusReduceView_edgeColor, Color.BLACK);
        leftDivider = typedArray.getDimension(R.styleable.GYPlusReduceView_leftDivider, 0);
        leftDividerColor = typedArray.getInteger(R.styleable.GYPlusReduceView_leftDividerColor, Color.BLACK);
        rightDivider = typedArray.getDimension(R.styleable.GYPlusReduceView_rightDivider, 0);
        rightDividerColor = typedArray.getInteger(R.styleable.GYPlusReduceView_rightDividerColor, Color.BLACK);
        divider = typedArray.getDimension(R.styleable.GYPlusReduceView_divider, 0);
        dividerColor = typedArray.getInteger(R.styleable.GYPlusReduceView_dividerColor, Color.BLACK);
        reduceSize = typedArray.getDimension(R.styleable.GYPlusReduceView_reduceSize, dp2px(getContext(), 14));
        plusSize = typedArray.getDimension(R.styleable.GYPlusReduceView_plusSize, dp2px(getContext(), 14));
        reduceDrawable = typedArray.getResourceId(R.styleable.GYPlusReduceView_reduceDrawable, 0);
        plusDrawable = typedArray.getResourceId(R.styleable.GYPlusReduceView_plusDrawable, 0);

        setGravity(Gravity.CENTER);
        setOrientation(LinearLayout.HORIZONTAL);
        setPadding(edgeWidthPx, edgeWidthPx, edgeWidthPx, edgeWidthPx);
        setBackground(getDrawable(backgroundColor, Math.round(edgeWidthPx), edgeColor, Math.round(radius)));

        reduceLL = linearLayout(Math.round(reduceWidth), MATCH_PARENT);
        numberLL = linearLayout(Math.round(numberWidth), MATCH_PARENT);
        plusLL = linearLayout(Math.round(plusWidth), MATCH_PARENT);

        reduceImageView = imageView(reduceDrawable, Math.round(reduceSize), Math.round(reduceSize));
        reduceTextView = textView("－", Math.round(reduceSize));
        reduceLL.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //减
                reduce();
            }
        });

        leftDividerView = view(Math.round(divider) == 0 ? Math.round(leftDivider) : Math.round(divider), dividerColor == 0 ? leftDividerColor : dividerColor);

        numberTextView = textView(String.valueOf(number), Math.round(numberSize));
        numberLL.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //数
                numberDialog();
            }
        });

        rightDividerView = view(Math.round(divider) == 0 ? Math.round(rightDivider) : Math.round(divider), dividerColor == 0 ? rightDividerColor : dividerColor);

        plusImageView = imageView(plusDrawable, Math.round(plusSize), Math.round(plusSize));
        plusTextView = textView("＋", Math.round(plusSize));
        plusLL.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //加
                plus();
            }
        });

        if (minNumber < maxNumber) {
            if (number == minNumber) {
                reduceTextView.setTextColor(noClickColor);
                plusTextView.setTextColor(clickColor);
            } else if (number == maxNumber) {
                reduceTextView.setTextColor(clickColor);
                plusTextView.setTextColor(noClickColor);
            } else if (number < minNumber) {
                number = minNumber;
                reduceTextView.setTextColor(noClickColor);
                plusTextView.setTextColor(clickColor);
            } else if (number > maxNumber) {
                number = maxNumber;
                reduceTextView.setTextColor(clickColor);
                plusTextView.setTextColor(noClickColor);
            } else {
                reduceTextView.setTextColor(clickColor);
                plusTextView.setTextColor(clickColor);
            }
        } else if (minNumber == maxNumber) {
            number = minNumber = maxNumber;
            reduceTextView.setTextColor(noClickColor);
            plusTextView.setTextColor(noClickColor);
        }
        if (minNumber > maxNumber) {
            minNumber = -99999;
            maxNumber = 99999;
            if (number < minNumber || number > maxNumber) {
                number = 1;
                reduceTextView.setTextColor(clickColor);
                plusTextView.setTextColor(clickColor);
            }
        }
        numberTextView.setText(String.valueOf(number));

        reduceLL.addView(reduceImageView);
        reduceLL.addView(reduceTextView);
        numberLL.addView(numberTextView);
        plusLL.addView(plusImageView);
        plusLL.addView(plusTextView);

        addView(reduceLL);
        addView(leftDividerView);
        addView(numberLL);
        addView(rightDividerView);
        addView(plusLL);

        reduceImageView.setVisibility(reduceDrawable == 0 ? GONE : VISIBLE);
        reduceTextView.setVisibility(reduceDrawable == 0 ? VISIBLE : GONE);
        plusImageView.setVisibility(plusDrawable == 0 ? GONE : VISIBLE);
        plusTextView.setVisibility(plusDrawable == 0 ? VISIBLE : GONE);
    }

    /**
     * 获取当前number
     *
     * @return
     */
    public int getNumber() {
        return number;
    }

    /**
     * 设置number
     *
     * @param number
     */
    public GYPlusReduceView setNumber(int number) {
        if (number < minNumber) {
            this.number = minNumber;
        } else if (number > maxNumber) {
            this.number = maxNumber;
        } else {
            this.number = number;
        }
//        if (onNumberChangedListener != null){
//            onNumberChangedListener.onNumberChanged(Integer.valueOf(numberTextView.getText().toString()),this.number);
//        }
        numberTextView.setText(String.valueOf(this.number));
        return this;
    }

    /**
     * 设置最小数
     * @param minNumber
     * @return
     */
    public GYPlusReduceView setMinNumber(int minNumber) {
        this.minNumber = minNumber;
        if (number < minNumber) {
            number = minNumber;
//            if (onNumberChangedListener != null){
//                onNumberChangedListener.onNumberChanged(Integer.valueOf(numberTextView.getText().toString()),number);
//            }
            numberTextView.setText(String.valueOf(number));
        }
        return this;
    }

    /**
     * 设置最大数
     * @param maxNumber
     * @return
     */
    public GYPlusReduceView setMaxNumber(int maxNumber) {
        this.maxNumber = maxNumber;
        if (number > maxNumber) {
            number = maxNumber;
//            if (onNumberChangedListener != null){
//                onNumberChangedListener.onNumberChanged(Integer.valueOf(numberTextView.getText().toString()),number);
//            }
            numberTextView.setText(String.valueOf(number));
        }
        return this;
    }

    /**
     * 数字变化监听
     *
     * @param onNumberChangedListener
     */
    public GYPlusReduceView setOnNumberChangedListener(OnNumberChangedListener onNumberChangedListener) {
        this.onNumberChangedListener = onNumberChangedListener;
        return this;
    }

    public interface OnNumberChangedListener {
        void onNumberChanged(int oldNumber, int number);
    }

    private void reduce() {
        if (number > minNumber) {
            number--;
            if (number == minNumber) {
                reduceTextView.setTextColor(noClickColor);
            }
            if (number < maxNumber) {
                plusTextView.setTextColor(clickColor);
            }
            if (onNumberChangedListener != null) {
                onNumberChangedListener.onNumberChanged(Integer.valueOf(numberTextView.getText().toString()), number);
            }
            numberTextView.setText(String.valueOf(number));
        }
    }

    private void plus() {
        if (number < maxNumber) {
            number++;
            if (number == maxNumber) {
                plusTextView.setTextColor(noClickColor);
            }
            if (number > minNumber) {
                reduceTextView.setTextColor(clickColor);
            }
            if (onNumberChangedListener != null) {
                onNumberChangedListener.onNumberChanged(Integer.valueOf(numberTextView.getText().toString()), number);
            }
            numberTextView.setText(String.valueOf(number));
        }
    }

    private void numberDialog() {
        final EditText inputEditText = new EditText(getContext());
        inputEditText.setSingleLine();
        inputEditText.setMaxLines(5);
        inputEditText.setGravity(Gravity.CENTER);
        inputEditText.setBackground(null);
        inputEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
        inputEditText.setHint(String.valueOf(number));
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("输入数量").setView(inputEditText)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (TextUtils.isEmpty(inputEditText.getText())) {
                    inputEditText.setText(inputEditText.getHint().toString());
                }
                if (Integer.valueOf(inputEditText.getText().toString()) < minNumber) {
                    number = minNumber;
                } else if (Integer.valueOf(inputEditText.getText().toString()) > maxNumber) {
                    number = maxNumber;
                } else {
                    number = Integer.valueOf(inputEditText.getText().toString());
                }
                if (onNumberChangedListener != null) {
                    onNumberChangedListener.onNumberChanged(Integer.valueOf(numberTextView.getText().toString()), number);
                }
                numberTextView.setText(String.valueOf(number));
            }
        });
        builder.show();
    }

    /**
     * 添加背景色、圆角、边框/颜色
     *
     * @param backgroundColor 背景色
     * @param strokeWidth     边框宽
     * @param strokeColor     边框颜色
     * @param radius          圆角度
     */
    private GradientDrawable getDrawable(int backgroundColor, int strokeWidth, int strokeColor, int radius) {
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setStroke(strokeWidth, strokeColor);
        if (radius != 0) {
            gradientDrawable.setCornerRadius(radius);
        }
        gradientDrawable.setColor(backgroundColor);
        return gradientDrawable;
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param context
     * @param pxValue （DisplayMetrics类中属性density）
     * @return
     */
    private int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param context
     * @param dipValue （DisplayMetrics类中属性density）
     * @return
     */
    private int dp2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param context
     * @param pxValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    private int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param context
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    private int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}
